package com.example.server.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.server.mapper.RoleMapper;
import com.example.common.pojo.Admin;
import com.example.common.pojo.Role;
import com.example.server.security.context.SecurityContextHolder;
import com.example.server.service.IAdminService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Component
public class TokenLoadingInterceptor implements HandlerInterceptor {
    @Autowired
    private SecurityContextHolder securityContextHolder;

    @Autowired
    private IAdminService adminService;

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authorization = request.getHeader("Authorization");
        if (!StringUtils.isEmpty(authorization)) {

            String token = authorization.substring("Bearer".length());

            Claims body = Jwts.parser()
                    .setSigningKey("test")
                    .parseClaimsJws(token)
                    .getBody();
            String username = body.getSubject();
            Admin admin = adminService.getOne(new QueryWrapper<Admin>().eq("username", username));

            if (admin != null) {
                List<Role> roles = roleMapper.findByAdminId(admin.getId());
                admin.setRoles(roles);
                securityContextHolder.setUserDetails(admin);
            }
        }
        return true;
    }
}
